<template>
    <div
        class="customerInfo"
        v-loading="loading3002 || loading3003"
        element-loading-background="rgba(255, 255, 255, 0.7)"
    >
        <cardComponent pageTitle="查询服务类-->客户资料修改">
            <template slot="cardBody">
                <el-form
                    class="customerInfoForm"
                    ref="customerInfoForm"
                    :model="customerInfoForm"
                    :rules="rules"
                    label-position="right"
                    size="small"
                    label-width="100px"
                >
                    <el-form-item label="主卡卡号:" label-position="left">
                        <el-input v-model="cardInfo_3004.CARDNO" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="客户姓名:" label-position="left" prop="CHINAME">
                        <el-input v-model="customerInfoForm.CHINAME" disabled></el-input>
                    </el-form-item>
                    <el-form-item label="手机号码:" label-position="left" prop="MOBILEPHONE">
                        <el-input
                            placeholder="请输入手机号码"
                            v-model.number="customerInfoForm.MOBILEPHONE"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="证件类型:" label-position="left" prop="KEYTYPE">
                        <el-select
                            placeholder="请选择证件类型"
                            v-model="customerInfoForm.KEYTYPE"
                            clearable
                        >
                            <el-option
                                v-for="(item, index) in keyTypeList"
                                :key="index"
                                :label="item.name"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="证件号:" label-position="left" prop="CUSTID">
                        <el-input placeholder="请输入证件号" v-model="customerInfoForm.CUSTID"></el-input>
                    </el-form-item>
                    <el-form-item label="出生日期:" label-position="left" prop="BIRTHDAY">
                        <el-date-picker
                            v-model="customerInfoForm.BIRTHDAY"
                            type="date"
                            placeholder="请选择出生日期"
                            format="yyyy-MM-dd"
                            value-format="yyyyMMdd"
                        ></el-date-picker>
                    </el-form-item>
                    <el-form-item label="性别:" label-position="left" prop="GENDER">
                        <el-radio-group v-model="customerInfoForm.GENDER">
                            <el-radio :label="'M'">男</el-radio>
                            <el-radio :label="'F'">女</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="地址:" label-position="left" class="addressContainer">
                        <el-form-item prop="ADDRESS1">
                            <el-input v-model="customerInfoForm.ADDRESS1"></el-input>
                        </el-form-item>
                        <el-form-item prop="ADDRESS2">
                            <el-input v-model="customerInfoForm.ADDRESS2"></el-input>
                        </el-form-item>
                        <el-form-item prop="ADDRESS3">
                            <el-input v-model="customerInfoForm.ADDRESS3"></el-input>
                        </el-form-item>
                        <el-form-item prop="ADDRESS4">
                            <el-input v-model="customerInfoForm.ADDRESS4"></el-input>
                        </el-form-item>
                        <el-form-item prop="ADDRESS5">
                            <el-input v-model="customerInfoForm.ADDRESS5"></el-input>
                        </el-form-item>
                    </el-form-item>
                    <el-form-item label="固定电话:" label-position="left" prop="HOMEPHONE">
                        <el-input
                            placeholder="请输入固定电话号码"
                            v-model.number="customerInfoForm.HOMEPHONE"
                        ></el-input>
                    </el-form-item>
                    <el-form-item label="电子邮箱:" label-position="left" prop="EMAIL">
                        <el-input placeholder="请输入电子邮箱" v-model="customerInfoForm.EMAIL"></el-input>
                    </el-form-item>
                    <el-form-item label="邮编:" label-position="left" prop="POSTCODE">
                        <el-input placeholder="请输入邮编" v-model="customerInfoForm.POSTCODE"></el-input>
                    </el-form-item>
                    <el-form-item label="学历:" label-position="left" prop="EDUCATION">
                        <el-select
                            placeholder="请选择学历"
                            v-model="customerInfoForm.EDUCATION"
                            clearable
                        >
                            <el-option
                                v-for="(item, index) in educationList"
                                :key="index"
                                :label="item.label"
                                :value="item.value"
                            ></el-option>
                        </el-select>
                    </el-form-item>

                    <div class="btnBox">
                        <el-button type="primary" size="small" @click="handleSubmit">修 改</el-button>
                        <el-button type="primary" size="small" @click="handleReset">重 置</el-button>
                    </div>
                </el-form>
            </template>
        </cardComponent>
    </div>
</template>
<script>
import { mapState } from 'vuex';
import cardComponent from '@/components/cardComponent/cardComponent.vue';
import { RegConfig } from '@/utils/RegConfig';
import { EDUCATION_LIST, ADDRESS_TYPE, PAPERS_TYPE } from '@/utils/Contants';
import { cardProductCheck } from '@/utils/menuRules';
import { getDictValue } from '@/utils/Common';

export default {
    name: 'customerInfo',
    components: {
        cardComponent,
    },
    data() {
        return {
            title: 'customerInfo',
            educationList: EDUCATION_LIST, // 学历选择列表
            loading3002: false, // 3002交易
            loading3003: false, //
            keyTypeList: PAPERS_TYPE,
            customerInfoForm: {
                STSMAIL: '', // 账单地址类型
                CHINAME: '', // 客户姓名
                MOBILEPHONE: '', // 手机号
                KEYTYPE: undefined, // 证件类型
                CUSTID: '', // 证件号码
                BIRTHDAY: '', // 出生日期
                GENDER: 'M', // 性别 M-男 F-女
                HOMEPHONE: '', // 固定电话
                EMAIL: '', // 电子邮箱
                EDUCATION: undefined, // 学历
                POSTCODE: '', // 邮编
                ADDTYPE: '', // 地址类型
                ADDRESS1: '', // 地址1
                ADDRESS2: '', // 地址2
                ADDRESS3: '', // 地址3
                ADDRESS4: '', // 地址4
                ADDRESS5: '', // 地址5
            },
            oldData: {}, // 上一次请求的数据 -- 用于比较新老地址的变化来判断 是否需要跑3003交易
            isUpdate: false,
            rules: {
                MOBILEPHONE: [
                    { pattern: RegConfig.mobile, message: '请输入11位有效手机号码', trigger: 'blur' },
                ],
                EMAIL: [
                    { pattern: RegConfig.email, message: '请输入正确的邮箱号', trigger: 'blur' },
                ],
            },
            baseParams: {}, // 接口请求报文默认参数
        };
    },

    // 取缓存信息
    computed: mapState({
        cardInfo_3004: state => state.common.cardInfo_3004, // 默认卡信息
        cardList_3601: state => state.common.cardList_3601, // 卡列表信息
        defaultParams: state => state.common.defaultParams, // 接口默认参数
        inlineParams: state => state.common.inlineParams, // 接口默认参数
        pinFlag: state => state.common.pinFlag, // 是否密码检查标志
    }),

    mounted() {
        this.init();
    },

    methods: {

        // 初始化
        async init() {
            // 查询数据库字典 获取 卡产品名称
            const productName = await getDictValue(this.cardList_3601, this.cardInfo_3004.CARDNO, 'PRODUCT', this);

            // 菜单校验
            const checkFlag = await cardProductCheck(productName, this.cardInfo_3004, this);

            if (checkFlag) {
                // 设置请求参数 -- M002 交易
                const appBody = {
                    OPTION: 1, // 1:查询 2：修改 3：按位图修改 4：新增（仅北京银行）按手机号码方式查询时，只能查询不能修改，也不能按位图修改
                    INQOPT: 1, // 查询方式 // 1-按卡号查询 2-按张建查询 3-按手机号码查询             //业务报文
                    CARDNBR: this.cardInfo_3004.CARDNO, // 卡号
                    PINFLAG: this.pinFlag, // 0-不检查密码 1-检查卡片级查询密码 2-检查取款密码 3-检查客户级查询密码
                };
                const params = JSON.parse(JSON.stringify(this.defaultParams));
                params.body.appHead.tranCode = '3002';
                params.body.appBody = appBody;
                this.baseParams = params;
                // 获取页面初始化查询数据
                this.getInitPageData();
            }
        },

        // 获取客户信息数据
        getInitPageData() {
            // 查询客户信息
            this.handleUpdateCustomerInfo();
        },

        // 表单数据处理
        handleSubmit() {
            if (this.loading3002 || this.loading3003) return;
            this.isUpdate = true;
            // 查询客户信息
            this.handleUpdateCustomerInfo();
        },

        // 查询-更新客户信息 3002 交易（不包括地址信息）
        handleUpdateCustomerInfo() {
            this.loading3002 = true;
            this.loading3003 = true;
            const params3002 = JSON.parse(JSON.stringify(this.baseParams));
            const params3003 = JSON.parse(JSON.stringify(this.baseParams));
            params3003.body.appHead.tranCode = '3003';
            let trans3002Flag = false;
            let trans3003Flag = false;
            const params1 = {
                CHINAME: '', // 客户姓名
                MOBILEPHONE: '', // 手机号
                KEYTYPE: undefined, // 证件类型
                CUSTID: '', // 证件号码
                BIRTHDAY: '', // 出生日期
                GENDER: 'M', // 性别 M-男 F-女
                HOMEPHONE: '', // 固定电话
                EMAIL: '', // 电子邮箱
                EDUCATION: undefined, // 学历
            };
            if (this.isUpdate) { // 作更新交易
                // 3002 交易参数处理------------------------------------------------------------

                // 将表单字段的值赋给params1
                for (const key in params1) {
                    params1[key] = this.customerInfoForm[key];
                }
                trans3002Flag = this.handleJudge(params1);
                if (trans3002Flag) {
                    const appBody = Object.assign(params1, params3002.body.appBody);
                    params3002.body.appBody = appBody;
                    params3002.body.appBody.OPTION = 2; // 修改
                }

                // 3003 交易参数处理------------------------------------------------------------
                const params2 = {};
                const addressData = {
                    STSMAIL: '', // 账单地址
                    ADDTYPE: '', // 地址类型
                    POSTCODE: '', // 邮编
                    ADDRESS1: '', // 地址1
                    ADDRESS2: '', // 地址2
                    ADDRESS3: '', // 地址3
                    ADDRESS4: '', // 地址4
                    ADDRESS5: '', // 地址5
                };
                for (const key in addressData) {
                    addressData[key] = this.customerInfoForm[key];
                }
                // 根据查询结果 匹配地址类型
                ADDRESS_TYPE.forEach((item) => {
                    if (item.value === addressData.STSMAIL) {
                        params2.STSMAIL = addressData.STSMAIL;
                        params2[`POSTCODE${item.id}`] = addressData.POSTCODE;
                        params2[`ADD${item.id}TYPE`] = addressData.ADDTYPE;
                        params2[`ADD${item.id}1`] = addressData.ADDRESS1;
                        params2[`ADD${item.id}2`] = addressData.ADDRESS2;
                        params2[`ADD${item.id}3`] = addressData.ADDRESS3;
                        params2[`ADD${item.id}4`] = addressData.ADDRESS4;
                        params2[`ADD${item.id}5`] = addressData.ADDRESS5;
                    }
                });
                trans3003Flag = this.handleJudge(addressData);
                if (trans3003Flag) { // 地址信息有变动 - 修改更新
                    const appBody = Object.assign(params2, params3003.body.appBody);
                    params3003.body.appBody = appBody;
                    params3003.body.appBody.OPTION = 2; // 修改
                }
            }
            console.log(params3002, '3002参数');
            console.log(params3003, '3002参数');


            // 跑 H002 交易
            if (trans3002Flag || trans3003Flag) {
                this.handleTranceH002();
            }

            // 做 3002 交易-- 接口
            if (!this.isUpdate || (this.isUpdate && trans3002Flag)) { // 首次交易（查询）或者用户信息发生改变十作3002交易
                this.handleTrance3002(params3002, params1);
            } else { // 释放按钮
                this.loading3002 = false;
            }

            // 做 3003 交易-- 接口
            if (!this.isUpdate || (this.isUpdate && trans3003Flag)) { // 首次交易（查询）或者用户信息发生改变十作3002交易
                if (params3003.body.appBody.OPTION === 2 && (this.customerInfoForm.ADDRESS1.trim() === '' || this.customerInfoForm.ADDRESS2.trim() === '')) {
                    this.$alert('地址行1和行2不能为空，请重新输入!', '提示', {
                        customClass: 'warning', type: 'warning',
                    });
                    this.loading3003 = false;
                    return;
                }
                this.handleTrance3003(params3003);
            } else { // 释放按钮
                this.loading3003 = false;
            }
        },

        // H002 交易接口
        handleTranceH002() {
            const formData = JSON.parse(JSON.stringify(this.customerInfoForm));
            const defaultParams = JSON.parse(JSON.stringify(this.inlineParams));
            const params = {
                cardAsn: this.cardInfo_3004.CARDNO, // 卡号
                idnoType: formData.KEYTYPE, // 证件类型
                idno: formData.CUSTID, // 证件号
                name: formData.CHINAME, // 客户姓名
                mobilePhone: formData.MOBILEPHONE, // 手机号
                birthday: formData.BIRTHDAY, // 出生日期
                gender: formData.GENDER, // 性别
                address: formData.ADDRESS1 + formData.ADDRESS2 + formData.ADDRESS3 + formData.ADDRESS4 + formData.ADDRESS5, // 地址
                zipcode: formData.POSTCODE, // 邮编
                industry: '', // 所属行业
                phone: formData.HOMEPHONE, // 固定电话
                email: formData.EMAIL, // 电子邮箱
                nativePlace: '', // 籍贯
                education: formData.EDUCATION, // 学历
            };
            defaultParams.body.appBody = params;
            defaultParams.body.appHead.tranCode = 'H002';
            this.$post.inlineTransModule.transH002(defaultParams).then((res) => {
                if (res.status === 200) { // 接口请求成功
                    const result = JSON.parse(res.data.jsonRes);
                    console.log(result, 'result--H002');
                    if (result.sysHead.rspCd === '000000') {
                        // for(let key in this.successData) {
                        //     this.successData[key] = result.body.appBody[key]
                        // }
                        // this.isShowSuccessDialog = true
                    } else {
                        const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                        this.$alert(errorMsg, result.sysHead.rspDesc, '提示', {
                            customClass: 'error', type: 'error',
                        });
                    }
                } else {
                    this.$message.error('请求失败');
                }
            });
        },

        // 3002 交易接口
        handleTrance3002(params, params1) {
            this.$post.common.transPort(params).then((res) => {
                this.loading3002 = false;
                this.isUpdate = true;
                if (res.status === 200) { // 请求成功
                    const result = JSON.parse(res.data.jsonRes);
                    // console.log(result, 'result1111111')
                    if (result.sysHead.rspCd === '000000') { // 交易成功
                        // console.log(result)
                        const data = result.body.appBody;

                        this.$store.commit('common/UPDATE_CUS_INFO', data);
                        console.log(data, 'result -- 3002');
                        // 客户信息数据处理 表单赋值
                        for (const key in params1) {
                            this.customerInfoForm[key] = data[key] ? data[key] : '';
                        }
                        this.customerInfoForm.BIRTHDAY = `${data.BIRTHDAY}`;
                        // 存储老数据
                        this.oldData = JSON.parse(JSON.stringify(this.customerInfoForm));
                        if (params.body.appBody.OPTION === 2) {
                            this.$alert('客户信息修改成功', '提示', {
                                customClass: 'success', type: 'success',
                            });
                        }
                    } else { // 交易失败
                        const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                        this.$alert(errorMsg, result.sysHead.rspDesc, '提示', {
                            customClass: 'error', type: 'error',
                        });
                    }
                } else { // 请求失败
                    this.$alert('请求失败!', '提示', {
                        customClass: 'error', type: 'error',
                    });
                }
            });
        },

        // 3003 交易接口
        handleTrance3003(params) {
            this.$post.common.transPort(params).then((res) => {
                this.loading3003 = false;
                if (res.status === 200) { // 请求成功
                    const result = JSON.parse(res.data.jsonRes);
                    console.log(result, 'result -- 3003');
                    if (result.sysHead.rspCd === '000000') { // 交易成功
                        // console.log(result)
                        const data = result.body.appBody;
                        // 地址信息数据处理 表单赋值
                        ADDRESS_TYPE.forEach((item) => {
                            if (item.value === data.STSMAIL) {
                                this.customerInfoForm.ADDRESS1 = data[`ADD${item.id}1`];
                                this.customerInfoForm.ADDRESS2 = data[`ADD${item.id}2`];
                                this.customerInfoForm.ADDRESS3 = data[`ADD${item.id}3`];
                                this.customerInfoForm.ADDRESS4 = data[`ADD${item.id}4`];
                                this.customerInfoForm.ADDRESS5 = data[`ADD${item.id}5`];
                                this.customerInfoForm.ADDTYPE = data[`ADD${item.id}TYPE`];
                                this.customerInfoForm.POSTCODE = data[`POSTCODE${item.id}`];
                                this.customerInfoForm.STSMAIL = data.STSMAIL;
                            }
                        });
                        this.oldData = JSON.parse(JSON.stringify(this.customerInfoForm));
                        if (params.body.appBody.OPTION === 2) {
                            this.$alert('客户地址信息修改成功', '提示', {
                                customClass: 'success', type: 'success',
                            });
                        }
                    } else { // 交易失败
                        const errorMsg = `错误代码：${result.sysHead.rspCd}, 错误信息：${result.sysHead.rspMsg}`;
                        this.$alert(errorMsg, '提示', {
                            customClass: 'error', type: 'error',
                        });
                    }
                } else { // 请求失败
                    this.$alert('请求失败!', '提示', {
                        customClass: 'error', type: 'error',
                    });
                }
            });
        },

        // 判断地址信息是否有更新 有-返回true 无-返回false
        handleJudge(newData) {
            let flag = false;
            for (const key in newData) {
                // 判断 只要有一个地址信息不相等 就跑接3003接口
                if (key !== 'OPTION' && key !== 'INQOPT' && (newData[key] !== this.oldData[key])) {
                    flag = true;
                }
            }
            return flag;
        },

        // 充值按钮点击事件处理
        handleReset() {
            // this.$refs.customerInfoForm.resetFields()
            // 只重置 地址 和 邮编、邮箱
            this.customerInfoForm.POSTCODE = ''; // 邮编
            this.customerInfoForm.EMAIL = ''; // 邮箱
            this.customerInfoForm.ADDRESS1 = ''; // 地址1
            this.customerInfoForm.ADDRESS2 = ''; // 地址2
            this.customerInfoForm.ADDRESS3 = ''; // 地址3
            this.customerInfoForm.ADDRESS4 = ''; // 地址4
            this.customerInfoForm.ADDRESS5 = ''; // 地址5
        },
    },
};
</script>
<style lang="scss">
.customerInfo {
    .customerInfoForm {
        .addressContainer {
            & > .el-form-item__content {
                display: flex;

                .el-form-item {
                    flex: 1;
                    margin-right: 6px;
                }
            }
        }

        .el-form-item__content {
            text-align: left;

            .el-select,
            .el-date-editor {
                width: 100%;
                max-width: 400px;
            }
        }
    }
}
</style>
<style rel="stylesheet/scss" lang="scss" scoped>
.customerInfo {
    min-height: 100%;
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;

    .customerInfoForm {
        .el-input {
            max-width: 400px;
        }

        .addressContainer {
            & > .el-form-item__content {
                display: flex;

                .el-form-item {
                    flex: 1;
                }
            }
        }

        .btnBox {
            text-align: center;
            margin-top: 50px;
        }
    }
}
</style>
